package com.codechuan.hallo_internal;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.codechuan.hallo_internal.common.Constant;
import com.codechuan.hallo_internal.entity.SysUserConfigNz;
import com.codechuan.hallo_internal.floatwindow.FloatWindowManager;
import com.codechuan.hallo_internal.ui.login.LoginActivity;
import com.codechuan.hallo_internal.utils.ContextUtil;
import com.codechuan.hallo_internal.utils.DialogUtil;
import com.codechuan.hallo_internal.utils.MyProjectHttpUtil;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.Executors;


/**
 * @Deprecated 登录页面
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        // 获取按钮事件
        setContentView(R.layout.activity_main);
        Button loginButton = findViewById(R.id.login);
        loginButton.setOnClickListener(this);
        // 获取开启内置防封选择框事件
        CheckBox checkBox = findViewById(R.id.open_ff);

        checkBox.setChecked(true);
        Constant.open_ff = checkBox.isChecked();

        // 获取主线程
        Constant.handler = new Handler(getMainLooper());
        // 初始化线程池
        Constant.executorService = Executors.newFixedThreadPool(50);
        // 读取配置文件
        HashMap<String, String> account = getAccount();
        TextView readKey = findViewById(R.id.key);
        readKey.setText(account.get("key"));
        TextView readAccount = findViewById(R.id.account);
        readAccount.setText(account.get("account"));
        // 初始化提示
        DialogUtil.showDialog(this,"初始化大数据Token库完成~");
    }




    @Override
    public void onClick(View view) {
        // 登录按钮
        if (R.id.login == view.getId()) {
            // 获取卡密
            TextView keyView = findViewById(R.id.key);
            String key = keyView.getText().toString();
            Constant.keyNumber = key;
            // 获取账号
            TextView accountView = findViewById(R.id.account);
            String account = accountView.getText().toString().replaceAll(" ", "");
            Constant.account = account;

            if (key.isEmpty()) {
                DialogUtil.showDialog(this, "卡密不能为空,请认真填写.");
                return;
            }
            if (account.isEmpty()) {
                DialogUtil.showDialog(this, "手机号不能为空,请认真填写.");
                return;
            }
            // 校验卡密
            new Thread(() -> {
                JSONObject result = MyProjectHttpUtil.login(key, account);
                if (result.getInteger("code") == 200) {
                    // 获取是否是最新版本
                    String version = result.getString("data");
                    if (Constant.app_version.equals(version)){
                        Constant.is_zx = true;
                    }
                    // 读取用户配置文件
                    SysUserConfigNz sysUserConfigNz = MyProjectHttpUtil.selectUserConfig(account);
                    if (sysUserConfigNz != null)
                    {
                        // 赋值给常量
                        if (sysUserConfigNz.getJdMs() != null) {
                            switch (sysUserConfigNz.getJdMs()) {
                                case "0":
                                    Constant.SN_ORDER = true;
                                    break;
                                case "1":
                                    Constant.CJ_ORDER = true;
                                    break;
                                case "2":
                                    Constant.XC_ORDER = true;
                                    break;
                            }
                        }
                        if (sysUserConfigNz.getPxGz() != null) {
                            switch (sysUserConfigNz.getPxGz()) {
                                case "1":
                                    Constant.ZN_PX_CHECK = true;
                                    break;
                                case "2":
                                    Constant.ZZ_CHECK = true;
                                    break;
                                case "3":
                                    Constant.ZJ_CHECK = true;
                                    break;
                                case "4":
                                    Constant.ZG_CHECK = true;
                                    break;
                            }
                        }
                        if (sysUserConfigNz.getRzMs() != null) {
                            switch (sysUserConfigNz.getRzMs()) {
                                case "1":
                                    Constant.APP_IS_CHECK = true;
                                    break;
                                case "2":
                                    Constant.XCX_IS_CHECK = true;
                                    break;
                            }
                        }
                        if (sysUserConfigNz.getZjDx() != null) {
                            Constant.ZJ_DX = !sysUserConfigNz.getZjDx().equals("0");
                        }

                        if (sysUserConfigNz.getYdGs() != null) {
                            Constant.YD_GS = !sysUserConfigNz.getYdGs().equals("0");
                        }

                        if (sysUserConfigNz.getQdDw() != null) {
                            Constant.QD_DW = !sysUserConfigNz.getQdDw().equals("0");
                        }

                        if (sysUserConfigNz.getMiniMoney() != null) {
                            Constant.MIN_MONEY = Integer.parseInt(sysUserConfigNz.getMiniMoney());
                        }

                        if (sysUserConfigNz.getMaxMoney() != null) {
                            Constant.MAX_MONEY = Integer.parseInt(sysUserConfigNz.getMaxMoney());
                        }

                        if (sysUserConfigNz.getDtStartDes() != null) {
                            Constant.DT_START_DES = Integer.parseInt(sysUserConfigNz.getDtStartDes());
                        }
                        if (sysUserConfigNz.getDtEndDes() != null) {
                            Constant.DT_END_DES = Integer.parseInt(sysUserConfigNz.getDtEndDes());
                        }

                        if (sysUserConfigNz.getXcZdJl() != null) {
                            Constant.XC_END_DES = Integer.parseInt(sysUserConfigNz.getXcZdJl());
                        }

                        if (sysUserConfigNz.getSld() != null) {
                            Constant.XC_SLD = Integer.parseInt(sysUserConfigNz.getSld());
                        }

                        if (sysUserConfigNz.getPcCsCheck() != null) {
                            Constant.PC_PERSON_CHECKBOX = !sysUserConfigNz.getPcGzCheck().equals("0");
                            Constant.PC_MIN_NUMBER = Integer.valueOf(sysUserConfigNz.getPcMinPerson());
                            Constant.PC_MAX_NUMBER = Integer.valueOf(sysUserConfigNz.getPcMaxPerson());
                        }

                        if (sysUserConfigNz.getSld() != null) {
                            Constant.XC_SLD = Integer.parseInt(sysUserConfigNz.getSld());
                        }

                        if (sysUserConfigNz.getDxGzCheck() != null) {
                            Constant.DX_PERSON_CHECKBOX = !sysUserConfigNz.getDxGzCheck().equals("0");
                            Constant.DX_MIN_NUMBER = Integer.valueOf(sysUserConfigNz.getDxMinPerson());
                            Constant.DX_MAX_NUMBER = Integer.valueOf(sysUserConfigNz.getDxMaxPerson());
                        }

                        if (sysUserConfigNz.getSsGzCheck() != null) {
                            Constant.SS_PERSON_CHECKBOX = !sysUserConfigNz.getSsGzCheck().equals("0");
                            Constant.SS_MIN_NUMBER = Integer.valueOf(sysUserConfigNz.getSsMinPerson());
                            Constant.SS_MAX_NUMBER = Integer.valueOf(sysUserConfigNz.getsMaxPerson());
                        }

                        if (sysUserConfigNz.getPcCsCheck() != null) {
                            Constant.PC_CS_CHECK = !sysUserConfigNz.getSsGzCheck().equals("0");
                            Constant.PC_CS_TEXT = sysUserConfigNz.getPcCsText();
                        }

                        if (sysUserConfigNz.getZdCsCheck() != null) {
                            Constant.ZD_CS_CHECK = !sysUserConfigNz.getZdCsCheck().equals("0");
                            Constant.ZD_CS_TEXT = sysUserConfigNz.getZdCsText();
                        }

                        if (sysUserConfigNz.getLxQd() != null) {
                            Constant.LX_QD = !sysUserConfigNz.getLxQd().equals("0");
                        }

                        if (sysUserConfigNz.getPcTh() != null) {
                            Constant.PC_TH_CHECK = !sysUserConfigNz.getPcTh().equals("0");
                        }

                    }

                    // 跳转到登录页
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                    // 初始化声音
                    Constant.mediaPlayer = MediaPlayer.create(this, R.raw.pk);
                    Constant.mediaPlayerPK = MediaPlayer.create(this, R.raw.zasn);
                    // 初始化卡密到期时间
                    MyProjectHttpUtil.selectUserExitTime(key);
                    // 保存配置
                    saveAcount(account, key);
                    //
                    Constant.is_login = true;
                } else {
                    Constant.handler.post(()->{
                        DialogUtil.showDialog(ContextUtil.context,result.getString("message"));
                    });
                }
                Constant.handler.post(() -> DialogUtil.showDialog(this, result.getString("message")));
            }).start();
            // 获取分辨率
            Constant.dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(Constant.dm);
            checkAndRequestPermission();
        }
    }

    private void checkAndRequestPermission() {
        if (!Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_CODE);
        } else {
            FloatWindowManager.get().showToolView();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (!Settings.canDrawOverlays(this)) {
                Constant.handler.post(() -> DialogUtil.showDialog(this, "请打开悬浮权限"));
            }
        }
    }

    private void saveAcount(String account, String key) {
        String fileName = "account.txt";
        String content = account + "," + key + ",";
        FileOutputStream fos = null;
        try {
            fos = this.openFileOutput(fileName, MODE_PRIVATE);
            fos.write((content.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private HashMap<String, String> getAccount() {
        String content = "";
        FileInputStream fis = null;
        try {
            fis = this.openFileInput("account.txt");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            content = new String(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        HashMap<String, String> hashMap = new HashMap<>();
        if (content.isEmpty()) {
            hashMap.put("account", "");
            hashMap.put("key", "");
        } else {
            String[] split = content.split(",");
            hashMap.put("account", split[0]);
            hashMap.put("key", split[1]);
        }
        return hashMap;
    }
}